<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios模拟实现</title>
</head>

<body>
    <script>

        function axios({ url, method = 'GET', params, data, headers }) {
            //返回一个 promise 对象
            return new Promise((resolve, reject) => {
                //创建 ajax 对象
                const xhr = new XMLHttpRequest();
                //对 params 处理
                let paramsStr = '?';
                if (params) {
                    for (let i in params) {
                        paramsStr += `${i}=${params[i]}&`;
                    }
                }
                //初始化请求
                xhr.open(method, url + paramsStr);
                //请求头
                if(headers){
                    //遍历 headers 对象
                    for(let i in headers){
                        xhr.setRequestHeader(i, headers[i]);
                    }
                }
                //声明 body 请求体变量
                let body = '';
                //判断
                if(typeof data === 'string'){
                    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
                    body = data;
                }

                if(typeof data === 'object'){
                    xhr.setRequestHeader('Content-type','application/json');
                    //将data转为json格式的字符串
                    body = JSON.stringify(data);
                }
                //请求体的处理
                xhr.send(body);
                //处理响应结果
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status < 300){
                            //成功的情况
                            resolve({
                                //配置
                                config: {method, url, params, data, headers},
                                //响应体
                                data: xhr.response,
                                //响应头
                                headers: xhr.getAllResponseHeaders(),
                                //本次请求使用 ajax 请求对象
                                request: xhr,
                                //响应状态码
                                status: xhr.status,
                                //响应状态字符串
                                statusText: xhr.statusText
                            });
                        }else{
                            //失败的情况
                            reject(xhr.status);
                        }
                    }
                }
            });
        }

        // axios({
        //     url: 'http://127.0.0.1/server',
        //     method: 'POST',
        //     headers:{
        //         a: 100,
        //         b: 200
        //     },
        //     params: { id: 1, vip: 9 }, //  => id=1&vip=9
        //     data: { username: 'xiaohigh' }
        //     // data: 'a=100&b=200'
        // }).then(response => {
        //     console.log(response);
        // })

        async function main(){
            let duanzi = await axios({
                url: 'https://api.apiopen.top/getJoke'
            });

            console.log(duanzi);
        }   
        
        main();
    </script>
</body>

</html>